package jp.co.mapion.conf;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.ReflectionException;

public class ConfigDynamicMBean implements DynamicMBean {

	private static final String INIT_METHOD_NAME = "init";

	private static final String INIT_MESSAGE = "Init Method";

	private static final String DESCRIPTION = "Can change the settings of the application";

	@Override
	public MBeanInfo getMBeanInfo() {
		MBeanAttributeInfo[] attributeInfos = new MBeanAttributeInfo[Conf.size()];
		int i = 0;
		for (Object key : Conf.keySet()) {
			attributeInfos[i++] = new MBeanAttributeInfo(key.toString(), String.class.getName(), key.toString(), true, true, false);
		}

		MBeanOperationInfo[] operationInfos = new MBeanOperationInfo[] {
				new MBeanOperationInfo(INIT_METHOD_NAME, INIT_MESSAGE, null, "void", MBeanOperationInfo.ACTION)
		};

		return new MBeanInfo(Conf.class.getName(), DESCRIPTION, attributeInfos, null, operationInfos, null);
	}

	@Override
	public Object getAttribute(String attribute)
			throws AttributeNotFoundException, MBeanException,
			ReflectionException {
		return Conf.get(attribute);
	}

	@Override
	public AttributeList getAttributes(String[] attributes) {
		AttributeList list = new AttributeList();
		for (String attribute : attributes) {
			try {
				list.add(new Attribute(attribute, getAttribute(attribute)));
			} catch (AttributeNotFoundException e) {
				e.printStackTrace();
			} catch (MBeanException e) {
				e.printStackTrace();
			} catch (ReflectionException e) {
				e.printStackTrace();
			}
		}

		return list;
	}

	@Override
	public void setAttribute(Attribute attribute)
			throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
		Conf.put(attribute.getName().toString(), attribute.getValue().toString());
	}

	@Override
	public AttributeList setAttributes(AttributeList attributes) {
		AttributeList list = new AttributeList(attributes);
		for (int i = 0, s = attributes.size(); i < s; i++) {
			Attribute attribute = (Attribute) attributes.get(i);
			try {
				setAttribute(attribute);
			} catch (Exception e) {
				list.remove(attribute);
			}
		}

		return list;
	}

	@Override
	public Object invoke(String actionName, Object[] params, String[] signature) {
		if (actionName.equals(INIT_METHOD_NAME)) {
		    Conf.init();
		}
	    return null;
	}
}
